// Copyright (c) 1996-2002 John Lyon-Smith. All rights reserved.

#pragma once

#include <wxtl\Base.h>
#include <wxtl\StringUtil.h>

namespace wxtl
{
	
	class HtmlTagChars
	{
	public:
		HtmlTagChars()
		{
			tagPrefix = _T("%");
			tagSuffix = _T("%");
			tagMultiPrefix1 = _T("<!--%");
			tagMultiPrefix2 = _T("<!--/%");
			tagMultiSuffix = _T("%-->");
		}

		tstring tagPrefix;
		tstring tagSuffix;
		tstring tagMultiPrefix1;
		tstring tagMultiPrefix2;
		tstring tagMultiSuffix;
		static HtmlTagChars s_tagChars;
	};
	
	_declspec(selectany) HtmlTagChars HtmlTagChars::s_tagChars;
	static inline HtmlTagChars& _stdcall getTagChars()
	{ 
		return HtmlTagChars::s_tagChars; 
	}

	////////////////////////////////////////////////////////////////////////////////////////

	inline bool _stdcall getMultiTag(tstring& strData, const tstring& strName, tstring& strBlock)
	{
		size_t i1 = 0;
		size_t i2 = 0;
		size_t j1 = 0;
		size_t j2 = 0;
		tstring strPat(getTagChars().tagMultiPrefix1 + strName + getTagChars().tagMultiSuffix);

		if ((i1 = strData.find(strPat)) == tstring::npos)
			return false;

		j1 = i1 + strPat.size();

		strPat = getTagChars().tagMultiPrefix2 + strName + getTagChars().tagMultiSuffix;

		if ((j2 = strData.find(strPat, j1)) == tstring::npos)
			return false;

		i2 = j2 + strPat.size();

		// Now build the new strings
		strBlock = strData.substr(j1, j2 - j1);
		substitute(strData, i1, i2 - i1, 
			(getTagChars().tagPrefix + strName + getTagChars().tagSuffix).c_str());

		return true;
	}

	inline void _stdcall replaceTags(tstring& str, hash_map<tstring, tstring>& mapVars)
	{
		for (hash_map<tstring, tstring>::iterator iter = mapVars.begin(); iter != mapVars.end(); iter++)
		{
			size_t i = 0;
			size_t j = 0;
			tstring strPat(getTagChars().tagPrefix + iter->first + getTagChars().tagSuffix);

			while ((j = str.find(strPat, i)) != tstring::npos)
			{
				substitute(str, j, strPat.size(), iter->second.c_str());
				i = j + iter->second.size();
			}
		}
	}
}